<template>
  <div class="hmi-only-select-table">
    <!-- 工具栏 -->
    <HmiTableToolbar
      v-if="showToolbar"
      :loading="loading"
      :show-refresh="true"
      :show-export="showExport"
      @refresh="handleRefresh"
      @export="handleExport"
    >
      <template #right-extra>
        <span v-if="total > 0" class="data-count">共 {{ total }} 条数据</span>
      </template>
    </HmiTableToolbar>

    <!-- 表格 -->
    <el-card shadow="hover" class="hmi-only-select-table__card">
      <el-table
        v-loading="loading"
        :data="tableData"
        :highlight-current-row="highlightCurrentRow"
        border
        class="hmi-only-select-table__card__content"
        empty-text="暂无数据"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
      >
        <!-- 选择列 -->
        <el-table-column
          v-if="selectable"
          type="selection"
          width="55"
          align="center"
          fixed="left"
        />

        <!-- 数据列 -->
        <el-table-column
          v-for="column in visibleColumns"
          :key="column.key"
          :prop="column.key"
          :label="column.label"
          :width="column.width"
          :min-width="column.minWidth || 120"
          align="left"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <!-- Boolean 类型显示为开关 -->
            <el-switch
              v-if="isBooleanColumn(row, column)"
              :model-value="Boolean(row[column.key])"
              :disabled="true"
              size="small"
              class="readonly-switch"
            />
            <!-- 其他类型显示为文本 -->
            <span v-else>
              {{ formatCellValue(row, column) }}
            </span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <!-- <div v-if="total > 0" class="pagination-wrapper"> -->
      <OffsetPagination
        v-if="total > 0"
        v-model:offset="pagination.offset"
        v-model:limit="pagination.limit"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        :layout="paginationLayout"
        class="hmi-only-select-table__card__pagination"
        @pagination="handlePaginationChange"
      />
      <!-- </div> -->
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { useHmiOnlySelectData } from "./composables/useHmiOnlySelectData";
import { isBooleanColumn, createCellFormatter } from "@/utils/hmi-data-table";
import { useTableExport, useErrorHandler } from "@/composables";
import type { HmiOnlySelectConfig, HmiOnlySelectRow, HmiOnlySelectColumnConfig } from "./types";

interface Props {
  config: HmiOnlySelectConfig;
  selectable?: boolean;
  showToolbar?: boolean;
  showExport?: boolean;
  highlightCurrentRow?: boolean;
}

interface Emits {
  (e: "data-loaded", data: HmiOnlySelectRow[]): void;
  (e: "selection-change", selection: HmiOnlySelectRow[]): void;
  (e: "row-click", row: HmiOnlySelectRow): void;
  (e: "error", error: Error): void;
}

const props = withDefaults(defineProps<Props>(), {
  selectable: false,
  showToolbar: true,
  showExport: true,
  highlightCurrentRow: true,
});

const route = useRoute();
const emit = defineEmits<Emits>();

// 错误处理
const { withErrorHandling } = useErrorHandler();

// 使用数据管理 composable
const {
  tableData,
  loading,
  total,
  selectedRows,
  pagination,
  data_status,
  DATA_STATUS,
  hasData,
  currentPage,
  fetchData,
  refreshData,
  handleSelectionChange: handleDataSelectionChange,
  handlePaginationChange,
} = useHmiOnlySelectData(props.config);

// 使用导出 composable
const { exportToExcel, generateExportColumns } = useTableExport();

// 统一的单元格格式化（参数化 valueKey/enumKey，默认 Value/Enum）
const valueKey = (props.config as any)?.valueKey ?? "Value";
const enumKey = (props.config as any)?.enumKey ?? "Enum";
const formatCellValue = createCellFormatter({ valueKey, enumKey });

// 可见列配置
const visibleColumns = computed(() =>
  props.config.columns.slice().sort((a, b) => (a.minWidth || 0) - (b.minWidth || 0))
);

// 分页布局：可配置隐藏 sizes
const paginationLayout = computed(() => {
  return props.config.pagination?.showSizeChanger === false
    ? "total, prev, pager, next, jumper"
    : "total, sizes, prev, pager, next, jumper";
});

// 事件处理
async function handleRefresh() {
  const result = await withErrorHandling(async () => {
    const data = await refreshData();
    emit("data-loaded", data || []);
    return data;
  }, "刷新数据");

  if (result) {
    ElMessage.success("刷新成功");
  }
}

// 导出表格数据
async function handleExport() {
  try {
    if (!tableData.value.length) {
      ElMessage.warning("暂无数据可导出");
      return;
    }

    // 生成导出列配置
    const columns = generateExportColumns(props.config.columns);
    const filename = route.meta.title as string;
    // 导出配置
    const exportConfig = {
      filename: `${filename}-${new Date().toISOString().slice(0, 10)}`,
      sheetName: `${filename}数据`,
      columns,
      data: tableData.value,
    };

    await exportToExcel(exportConfig);
  } catch (error) {
    console.error("导出失败:", error);
    ElMessage.error("导出失败，请重试");
  }
}

function handleSelectionChange(selection: HmiOnlySelectRow[]) {
  handleDataSelectionChange(selection);
  emit("selection-change", selection);
}

function handleRowClick(row: HmiOnlySelectRow) {
  emit("row-click", row);
}

function handleSizeChange() {
  handlePaginationChange();
}

function handleCurrentChange() {
  handlePaginationChange();
}

// 初始化数据
withErrorHandling(async () => {
  console.log("HmiOnlySelectTable: 初始化数据");
  if (data_status.value == DATA_STATUS.WAITING) {
    console.log("HmiOnlySelectTable: 数据状态为等待，开始获取数据");
    const data = await fetchData();
    if (data) {
      emit("data-loaded", data);
    }
    return data;
  }
}, "初始化数据");
</script>

<style lang="scss" scoped>
.hmi-only-select-table {
  /* width: 100%; */
  /* height: 100%; */
  &__toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding: 0 4px;

    &__left {
      display: flex;
      gap: 8px;
    }

    &__right {
      display: flex;
      align-items: center;
    }
  }

  &__card {
    &__content {
      width: 100%;
    }

    &__pagination {
      margin-top: 16px;
      display: flex;
      justify-content: flex-end;
    }
  }
}

.data-count {
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.data-table {
  width: 100%;
}

.readonly-switch {
  opacity: 0.8;
}

/* 隐藏水平滚动条 */
:deep(.el-scrollbar__bar.is-horizontal) {
  display: none !important;
}

/* 隐藏垂直滚动条 */
:deep(.el-scrollbar__bar.is-vertical) {
  display: none !important;
}
</style>
